﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Paros.Domain;
using Paros.Utils;
using WeifenLuo.WinFormsUI.Docking;
using Paros.BLL;
namespace Paros.Win
{
    public partial class mainForm : Form
    {
        private RibbonStyle.ThemeManager themeManager;
        private CategoryForm categoryForm;
        private ViewForm viewForm;
        private NewForm editorForm;
        private EntryListForm entryListForm;
        private PropertyForm propertyForm;
        private DeserializeDockContent m_deserializeDockContent;
        const string DockConfigurationFile = "Paros.Dock.Config";
        public mainForm()
        {
            InitializeComponent();
            categoryForm = new CategoryForm();
            entryListForm = new EntryListForm();
            propertyForm = new PropertyForm();
            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
        }

        public void OnCategoryChanged()
        {
            entryListForm.LoadData();
        }

        private string GetActiveDocumentId()
        {
            string res = string.Empty;
            IDockContent activeDoc = dockPanel1.ActiveDocument;

            if (activeDoc != null)
            {
                res = activeDoc.DockHandler.GetHashCode().ToString();
            }
            return res;

        }

        private string GetActiveEditorText()
        {
            IDockContent activeDoc = dockPanel1.ActiveDocument;
            return ((NewForm)activeDoc).Editor.BodyHtml;
        }

        public void OnEntryChanged(EntryItem entry)
        {
            IDockContent activeDoc;
            activeDoc = dockPanel1.ActiveDocument;
            if (dockPanel1.DocumentsCount == 0 || activeDoc.GetType() != typeof(ViewForm))
            {
                OpenEntry();
                activeDoc = dockPanel1.ActiveDocument;
                
            }
            activeDoc.DockHandler.TabText = entry.Title;
            if(propertyForm != null)
                propertyForm.SelectObject = entry;
            if (entry.Title.EndsWith(".url"))
            {
                string url = GetUrl(entry.Content);
                ((ViewForm)activeDoc).Editor.Navigate(url);
            }
            else
                ((ViewForm)activeDoc).Editor.DocumentText = entry.Content;
        }

        private string GetUrl(string content)
        {
            if (content.StartsWith("[InternetShortcut]"))
            {
                content = content.TrimEnd();
                int posStart = content.IndexOf("URL=");
                return content.Substring(posStart + 4);
            }

            return "about:blank";
        }

        public void OpenNewEntry(EntryItem entry)
        {
            IDockContent activeDoc;
            OpenEntry();
            activeDoc = dockPanel1.ActiveDocument;
            activeDoc.DockHandler.TabText = entry.Title;
            if (propertyForm != null)
                propertyForm.SelectObject = entry;
            ((ViewForm)activeDoc).Editor.DocumentText = entry.Content;
        }

        public void OnDocumentChanged()
        {
            IDockContent activeDoc = dockPanel1.ActiveDocument;
            string controlId = GetActiveDocumentId();
            bool docStatus = false;
            if (UserPreferences.DocumentList.Documents.ContainsKey(controlId))
            {
                docStatus = UserPreferences.DocumentList.Documents[controlId];
                if (docStatus)
                {
                    UserPreferences.DocumentList.Documents[controlId] = false;
                    activeDoc.DockHandler.TabText = activeDoc.DockHandler.TabText + " *";
                }
            }
            else
            {
                UserPreferences.DocumentList.Documents.Add(controlId, docStatus);
                activeDoc.DockHandler.TabText = activeDoc.DockHandler.TabText + " *";
            } 
            
        }

        public void OnDocumentSaving()
        {
            SaveEntry();
           
        }

        public void OnCategoryCountChanged(EntryItem entry)
        {
            categoryForm.RefreshCategoryCount(entry.Category.CategoryID.ToString());
        }

        private DockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof(CategoryForm).ToString())
                return categoryForm;
            else if (persistString == typeof(EntryListForm).ToString())
                return entryListForm;
            else if (persistString == typeof(PropertyForm).ToString())
                return propertyForm;
            return null;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //categoryForm.Show(dockPanel1, DockState.DockLeft);
            //entryListForm.Show(dockPanel1, DockState.DockLeft);
            //propertyForm.Show(dockPanel1, DockState.DockRightAutoHide);

            //ToolStripManager.Renderer = new Office2007Renderer.Office2007Renderer();

            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), DockConfigurationFile);

            if (File.Exists(configFile))
                dockPanel1.LoadFromXml(configFile, m_deserializeDockContent);

            themeManager = new RibbonStyle.ThemeManager(this, new Control[]{tabPageSwitcher1, tabStrip1, statusStrip1});
            themeManager.SetStyle("Mike");

        }

        private void lbThemes_SelectedIndexChanged(object sender, EventArgs e)
        {
            themeManager.SetStyle(lbTheme.Text);
        }

        private void rbEntryNew_Click(object sender, EventArgs e)
        {
            NewEntry();
            
        }

        public void NewEntry()
        {
            EntryItem item = new EntryItem();
            item.Category = UserPreferences.SelectedCategory;
            if (item.Category != null)
            {
                editorForm = new NewForm();
                editorForm.Category = item.Category.CategoryName;
                editorForm.TabText = "Note " + (dockPanel1.DocumentsCount + 1) + " *";
                editorForm.Show(dockPanel1);
                string controlId = GetActiveDocumentId();
                UserPreferences.DocumentList.Documents.Add(controlId, false);

                //if (propertyForm != null)
                //    propertyForm.SelectObject = item;
            }
        }

        private void OpenEntry()
        {
            viewForm = new ViewForm(); //SimpleEditorForm();//EditorForm();
            viewForm.TabText = "Note" + (dockPanel1.DocumentsCount + 1);
            viewForm.Show(dockPanel1);
            string controlId = GetActiveDocumentId();
            UserPreferences.DocumentList.Documents.Add(controlId, true);
        }

        private void SaveEntry()
        { 
            IDockContent activeDoc = dockPanel1.ActiveDocument;
            string controlId = GetActiveDocumentId();
            if (controlId == string.Empty)
                return;
            bool docStatus = false;
            docStatus = UserPreferences.DocumentList.Documents[controlId];
            // if active document hasn't been saved then do save process
            if (!docStatus)
            {
                NewForm editor = activeDoc as NewForm;
                EntryItem entry = new EntryItem(); //propertyForm.SelectObject as EntryItem;
                entry.Content = editor.Editor.BodyHtml;
                entry.ModifiedTime = DateTime.Now;
                entry.Title = editor.Title;
                entry.Category = UserPreferences.SelectedCategory;
                entry.ID = editorForm.ID;
                if (entry.Title == null || entry.Title.Length == 0)
                {
                    MessageHelper.ShowError("Please input 'Title' information");
                    return;
                }

                EntryMgr entryMgr = new EntryMgr();
                int res = 0;
                if (entry.ID < 1)
                {
                    res = entryMgr.SaveEntry(entry);
                    if (res == 1)
                    {
                        UserPreferences.DocumentList.Update(controlId, true);
                        OnCategoryChanged();
                        OnCategoryCountChanged(entry);
                        MessageHelper.ShowMessage("New entry has been saved successfully");
                        activeDoc.DockHandler.Close();
                        OnEntryChanged(entryMgr.GetLastEntry());
                    }
                }
                else
                {
                    res = entryMgr.UpdateEntry(entry);
                    if (res == 1)
                    {
                        UserPreferences.DocumentList.Update(controlId, true);
                        OnCategoryChanged();
                        MessageHelper.ShowMessage("The entry has been updated successfully");
                        activeDoc.DockHandler.Close();
                        OnEntryChanged(entryMgr.GetEntryById(entry.ID));
                    }
                }
                
            }
        }

        private void rbEntrySave_Click(object sender, EventArgs e)
        {
            SaveEntry();
        }

        private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            dockPanel1.SaveAsXml(DockConfigurationFile);
        }

        private void rbViewReset_Click(object sender, EventArgs e)
        {
            dockPanel1.SuspendLayout(true);

            CloseAllContents();

            Assembly assembly = Assembly.GetAssembly(typeof(mainForm));
            using (Stream xmlStream = assembly.GetManifestResourceStream("Paros.Win.Resources.DefautlDock.config"))
            {
                dockPanel1.LoadFromXml(xmlStream, m_deserializeDockContent);
            }

            dockPanel1.ResumeLayout(true, true);
        }

        private void CloseAllContents()
        {
            categoryForm.DockPanel = null;
            entryListForm.DockPanel = null;
            propertyForm.DockPanel = null;

            categoryForm = new CategoryForm();
            entryListForm = new EntryListForm();
            propertyForm = new PropertyForm();
            CloseAllDocuments();
        }

        private void CloseAllDocuments()
        {
            if (dockPanel1.DocumentStyle == DocumentStyle.SystemMdi)
            {
                foreach (Form form in MdiChildren)
                    form.Close();
            }
            else
            {
                IDockContent[] documents = dockPanel1.DocumentsToArray();
                foreach (IDockContent content in documents)
                    content.DockHandler.Close();
            }
        }

        private void cbViewEntryList_CheckedChanged(object sender, EventArgs e)
        {
            entryListForm.DockPanel = null;
            entryListForm = new EntryListForm();
            if (cbViewEntryList.Checked)
            {         
                entryListForm.Show(dockPanel1, DockState.DockTop); 
            }
        }

        private void cbViewCategory_CheckedChanged(object sender, EventArgs e)
        {
            categoryForm.DockPanel = null;
            categoryForm = new CategoryForm();
            if (cbViewCategory.Checked)
            {
                categoryForm.Show(dockPanel1, DockState.DockLeft);
            }
        }

        private void cbViewProperty_CheckedChanged(object sender, EventArgs e)
        {
            propertyForm.DockPanel = null;
            propertyForm = new PropertyForm();
            if (cbViewProperty.Checked)
            {
                propertyForm.Show(dockPanel1, DockState.DockRight);
            }
        }

        private void rbEntryDelete_Click(object sender, EventArgs e)
        {
            OnEntryDelete();
        }

        private void rbImportIE_Click(object sender, EventArgs e)
        {
            ImportIEForm ieForm = new ImportIEForm();
            ieForm.Show(this);
        }

        private void rbEntryEdit_Click(object sender, EventArgs e)
        {
            OnEntryEdit();
        }

        public void OnEntryEdit()
        {
            if (UserPreferences.SelectedEntry != null)
            {
                EntryItem item = UserPreferences.SelectedEntry;

                editorForm = new NewForm();
                editorForm.ID = item.ID;
                editorForm.Category = item.Category.CategoryName;
                editorForm.TabText = item.Title;
                editorForm.Title = item.Title;
                editorForm.Editor.DocumentText = item.Content;
                editorForm.Show(dockPanel1);
                string controlId = GetActiveDocumentId();
                UserPreferences.DocumentList.Documents.Add(controlId, true);

            }
        }

        public void OnEntryDelete()
        {
            if (UserPreferences.SelectedEntry == null)
                return;
            if (DialogResult.Yes == MessageHelper.ShowConfirmation("Are you sure to delete entry [" + UserPreferences.SelectedEntry.Title + "]?"))
            {
                EntryMgr mgr = new EntryMgr();
                int res = 0;
                res = mgr.DeleteEntry(UserPreferences.SelectedEntry);
                if (res > 0)
                {
                    OnCategoryChanged();
                    OnCategoryCountChanged(UserPreferences.SelectedEntry);
                    dockPanel1.ActiveDocument.DockHandler.DockPanel = null;
                }
            }
        }


    }
}
